<?php

namespace App\Modules\Admin\Services\Mall;

use App\Exceptions\Exception;
use app\model\goods\Goods;
use App\Modules\Admin\Entities\Mall\GoodsCateModel;
use App\Modules\Admin\Entities\Mall\GoodsContentModel;
use App\Modules\Admin\Entities\Mall\GoodsModel;
use App\Modules\Admin\Entities\Mall\GoodsRuleModel;
use App\Modules\Admin\Entities\Mall\GoodsRuleTplModel;
use App\Modules\Admin\Entities\Water\WaterDeviceModel;
use App\Modules\Admin\Http\Controllers\Mall\GoodsRuleExtendModel;
use App\Modules\Admin\Services\BaseService;
use http\Params;
use Illuminate\Support\Facades\DB;

class GoodsServices extends BaseService
{
    public function __construct(GoodsModel $model)
    {
        $this->model = $model;
        $this->with=['cate_info'];
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            if (!empty($search = $request->input('search', ''))){
                $query->where('goods_name', 'LIKE', '%' . trim($search) . '%');
            }
            if (!empty($uid = $request->input('uid', ''))){
                $query->where('user_id',$uid);
            }
            if (!empty($cate_id = $request->input('cate_id', ''))){
                $query->where('cate_id', $cate_id);
            }
            if (!empty($cate_id = $request->input('cate_id', ''))){
                $query->where('cate_id', $cate_id);
            }
        };

        return parent::lists($params); // TODO: Change the autogenerated stub
    }
    public function create(array $params)
    {
        $detail = $params['rule_extend'];
        $rule_attrs = $params['rule_attrs'];
        $goods_content = $params['goods_content'];
        $slider_image = json_encode($params['slider_image']);

        $cate_id = implode(',', $params['cate_id']);

        DB::beginTransaction();
        try{
            $baseParam = [
                'goods_name' => $params['goods_name'],
                'goods_no' => $params['goods_no']??"",
                'cate_id' => $cate_id??0,
                'unit' => $params['unit'],
                'slider_image' => $slider_image,
                'goods_img' => $slider_image[0],
                'spec_type' => $params['spec_type']??0,
                'is_show' => $params['is_show'],
                'is_hot' => $params['is_hot']??0,
                'is_recommend' => $params['is_recommend']??0,
                'is_new' => $params['is_new']??0,
                'spu' => $this->createSpu(),
            ];
            $this->detail = parent::create($baseParam); // TODO: Change the autogenerated stub
            $this->goodsRuleExtend($params,$this->detail->goods_id);

            $resContent = $this->dealGoodsContent($this->detail->goods_id,$goods_content);

            if ($resContent['code']){
                DB::rollBack();
                $this->error=$resContent['msg'];
                return false;
            }

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }
    public function goodsRuleExtend($param,$goods_id,$mode='edit')
    {
        $goodsStock = 0;
        $priceMap = [];
        $card_price = [];
        $originalPriceMap = [];
        if ($param['spec_type'] == 2) {
            $goodsRuleModel = new GoodsRuleModel();
            $goodsRuleMap = [
                'goods_id' => $goods_id,
                'rule_value' => json_encode($param['rule_attrs'])
            ];
//
            $goodsRuleHas = $goodsRuleModel->where(['goods_id' => $goods_id])->first();
            if (empty($goodsRuleHas)) {
                $goodsRuleRes = $goodsRuleModel->createGoodsRule($goodsRuleMap);
            } else {
                $goodsRuleRes = $goodsRuleModel->updateGoodsRule($goods_id,$goodsRuleMap);
            }
            if (!$goodsRuleRes) {
                return ['code'=>1,'msg'=>'规格错误'];
            }
            $goodsRuleExtendModel = new GoodsRuleExtendModel();
            $goodsRuleExtendModel->deleteGoodsRuleExtend($goods_id);
            $rule_extend = $param['rule_extend'];
            foreach ($rule_extend as $vo) {
//                $itemParam = [];
                $itemParam['sku'] = implode(',', $vo['sku']);
                $itemParam['goods_id'] = $goods_id;
                $itemParam['unique'] = uniqid();
                $itemParam['price'] = $vo['price'];
                $itemParam['card_price'] = $vo['card_price'];
                $itemParam['stock'] = $vo['stock'];
                $itemParam['image'] = $vo['image'] ?? '';
                $itemParam['cost_price'] = $vo['cost_price'];
                $itemParam['original_price'] = $vo['original_price'];
                $itemParam['weight'] = $vo['weight'];
                $itemParam['volume'] = $vo['volume'];
                $itemParam['spu'] = $vo['spu'];

                $goodsStock += $vo['stock'];
                $priceMap[] = $vo['price'];
                $card_price[] = $vo['card_price'];
                $originalPriceMap[] = $vo['original_price'];
                 $goodsRuleExtendModel->createGoodsRuleExtend($itemParam);

            }

        }
        $ruleParam = [
            'spec_type' => $param['spec_type'],
            'price' => $param['price']??0,
            'cost_price' => $param['cost_price']??0,
            'card_price' => $param['card_price']??0,
            'original_price' => $param['original_price']??0,
            'stock' => $param['stock']??0,
            'spu' => $param['spu']??"",
            'is_hot' => $param['is_hot']??0,
            'is_recommend' => $param['is_recommend']??0,
            'is_new' => $param['is_new']??0,
        ];
        if ($param['spec_type'] == 2) {
            $ruleParam['stock'] = $goodsStock;
            $ruleParam['card_price'] = min($card_price);
            $ruleParam['price'] = min($priceMap);
            $ruleParam['original_price'] = min($originalPriceMap);
        }
        $this->model->updateGoodsInfo($goods_id,$ruleParam);
//        if (!){
//            return ['code'=>1,'msg'=>'规格错误'];
//        }
        return ['code'=>0];
    }
    public function update(array $params)
    {
        $goods_content = $params['goods_content'];
        $slider_image = json_encode($params['slider_image']);

        $cate_id = implode(',', $params['cate_id']);

        $goods_id = $params['goods_id'];
        $baseParam = [
            'goods_id' => $goods_id,
            'goods_name' => $params['goods_name'],
            'cate_id' => $cate_id??0,
            'unit' => $params['unit'],
            'slider_image' => $slider_image,
            'is_show' => $params['is_show'],
            'spec_type' => $params['spec_type']??0,
            'is_recommend' => $params['is_recommend']??0,
        ];
        DB::beginTransaction();
        try{
            parent::update($baseParam); // TODO: Change the autogenerated stub
            $rule_res = $this->goodsRuleExtend($params,$goods_id);

            if ($rule_res['code']==1){
                DB::rollBack();
                $this->error = $rule_res['msg'];
                return false;
            }
            $resContent = $this->dealGoodsContent($goods_id,$goods_content);

            if ($resContent['code']){
                DB::rollBack();
                $this->error=$resContent['msg'];
                return false;
            }

            DB::commit();
            return true;
        }catch (Exception $e){
            DB::rollBack();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * 处理商品详情
     * @param array $param
     * @param string $mode
     * @return array
     */
    private function dealGoodsContent($goods_id,$content): array
    {
        $contentMap = [
            'goods_id' => $goods_id,
            'content' => $content
        ];

        $goodsContentModel = new GoodsContentModel();
        $goodsRuleHas = $goodsContentModel->where(['goods_id' => $goods_id])->first();
        if ($goodsRuleHas) {
            $res = $goodsContentModel->where(['goods_id'=>$goods_id])->update($contentMap);
        } else {
            $res = $goodsContentModel->create($contentMap);
        }
        if (!$res) {
            return ['code'=>1,'msg'=>'详情错误'];
        }

        return ['code'=>0];
    }

    /**
     * 处理其他数据
     * @param array $param
     * @param string $mode
     * @return array
     */
    private function dealOther(array $param, string $mode): array
    {
        $otherMap = [
            'goods_id' => $param['goods_id'],
            'seo_title' => $param['seo_title'],
            'seo_keywords' => $param['seo_keywords'],
            'seo_desc' => $param['seo_desc'],
            'is_hot' => $param['is_hot'],
            'is_recommend' => $param['is_recommend'],
            'is_new' => $param['is_new'],
            'user_label' => $param['label_id']
        ];


        $res = $this->model->where(['goods_id'=>$param['goods_id']])->update($otherMap);
        if ($res) {
            return ['code'=>1];
        }

        return ['code'=>1];
    }
    public function detail($request){
        $id = $request->input('goods_id', 0);
        $return=[];

        if ($id) {
            $productInfo = $this->model->detail($id, '*', false);

            $productInfo['cate_id'] = explode(',', $productInfo['cate_id']);
            $productInfo['slider_image'] = json_decode($productInfo['slider_image'],true);

            exit(json_encode($productInfo));

            if ($productInfo['spec_type'] == 1) {



            }else{

            }
            unset($productInfo['content_info']);
            unset($productInfo['extend_info']);
            $return = [
                'info' => $productInfo,
                'rule_extend' => $productInfo['extend_info'] ?? [],
            ];
            $return['info']['goods_contents'] = $productInfo['content_info']['content']??[];
            $ruleData =  GoodsRuleModel::getInstance()->where(['goods_id'=>$id])->first();

            $return['rule_info'] = json_decode($ruleData['rule_value'],true);
        }
        return $return;
    }

    /**
     * SPU
     * @return string
     */
    public function createSpu()
    {
        return substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . str_pad((string)mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
    }

}
